<?php
/*
 * Created on Oct 22, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
require_once("facebook_include1.php");
require('Postmark.php');

function login($access_token){
	try{
		global $user_id,  $userName ,$email;
		$temp = get_uid($access_token);
		foreach($temp['data'] as $status)
		{
			$user_id=$status['uid'];
		}
		$conn = connectdb();
		$userName = getUserName($user_id);
		$email= get_email($user_id);
		closedb($conn);
	}catch(Exception $e){
		echo "Exception";
	}	
}
function getUserName($user_id){
	global $user_id;
        //$conn = connectdb();
	$query = "SELECT Name  FROM user WHERE uid =  " . $user_id;
	$result = mysql_query($query);
	$row = mysql_fetch_array($result);
        //closedb($conn);
	return $row['Name'];
}
function get_email($user_id){
	global $user_id;
        //$conn = connectdb();
	$query = "SELECT email  FROM user WHERE uid =  " . $user_id;
	$result = mysql_query($query);
	$row = mysql_fetch_array($result);
        //closedb($conn);
	return $row['email'];
}
function isUserAddedToApp($userid){
	$conn = connectdb();
	$count = isUserAdded($userid);
	closedb($conn);
	return $count;
}

function isUserAdded($userid){
	$uid=floatval($userid);
	$sql = "SELECT UID FROM u_users WHERE uid = " . $uid;
	$result = mysql_query($sql);
	$count=mysql_num_rows ($result);
	return $count;
}

function isMaxUsersReached(){
	$conn = connectdb();
	$noOfUsers = getUserCount();
	closedb($conn);
	if($noOfUsers >= maxusers)
	return True;
	else
	return False;

}

function getUserCount(){
	$sql = "select uid from u_users";
	$result = mysql_query($sql);
	$count = mysql_num_rows ($result);
	return $count;
}

function createUser($uid, $name ,$email , $payment_type , $paypal_id, $address1 , $address2 , $city , $state  ,$country , $zip ){
	$conn = connectdb();
	$sql = "INSERT INTO u_users " .
			  "(uid, name ,email , payment_type , paypal_id, address1 , address2 , city , state  ,country , zip,balance ) " .
				"VALUES ('$uid', '$name' ,'$email' , '$payment_type' , '$paypal_id', '$address1' , '$address2' , '$city' , '$state'  ,'$country' , '$zip',0)";
	$result = mysql_query($sql);
	if (!$result) {
		echo('Invalid query create user: ' . mysql_error());
	}
	closedb($conn);

}
function Auth ($user_id,$password){

$conn = connectdb();
$auth_row=getUserAuth($user_id,$password);
return $auth_row;
}
function getUserAuth($user_id,$password){
	global $user_id;
	$query = "SELECT Name FROM user WHERE username= " . $user_id ."and password_sha1=".$password;
	$result = mysql_query($query);
	$row = mysql_fetch_array($result);
	return $row;
}



/* Functions for admin page  */
function getName($id){
	$conn = connectdb();
	$sql = "select Name from user where uid=".$id;
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	return $row['Name'];
}

function getEmail($id){
	$conn = connectdb();
	$sql = "select email from u_users where uid = ".$id;
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	$email = $row['email'];
	//closedb($conn);
	return $email;
}
function findIfSender($userId){
	$conn = connectdb();
	$sql = "select count(*) from u_gameplay where senderid =". $userId;
        //echo $sql. '<br/>';
	$result = mysql_query($sql);
	$temp = mysql_fetch_array($result);
	$count = $temp[0];
	//echo 'isSenderFunction  ' . $count . '   ' .$userId. '<br/>';
        closedb($conn);
	if($count > 0)
	return True;
	else
	return False;
}

function isGamePlayed($userId){
	$isSender = findIfSender($userId);
	$conn = connectdb();
	$sql = "";
	$returnValue = 0;
	if($isSender)
	$sql = "select * from u_gameplay where senderid = '$userId'";
	else
	$sql = "select * from u_gameplay where receiverid = '$userId'";
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	if($row == null)
	return 0;
	else{
		$returnValue = intval($row['stateid']);
	}
	closedb($conn);
	return $returnValue;
}

function logEvent($userId1, $userId2, $amount, $event){
        $conn = connectdb();
	if($event != 2){
		$sql = "INSERT INTO u_logs (userid1, userid2, amount, event) VALUES ('$userId1', '$userId2', '$amount','$event')";
		$result = mysql_query($sql);
	}
        closedb($conn);
}

function getReceiverId($senderid){
	$conn = connectdb();
	$sql = "SELECT * FROM u_gameplay where senderid = '$senderid'";
	$result = mysql_query($sql);
	if(!$result){
		echo ('Invalid query:' . mysql_error());
	}else{
		$row = mysql_fetch_assoc($result);
		closedb($conn);
		return $row['receiverid'];
	}
	closedb($conn);
	return null;

}

function isFriends ($userId, $receiverid)
{
    $conn = connectdb();
    $sql = "SELECT * FROM friends WHERE (UID =".$userId . " AND FID = ".$receiverid. ") OR (UID =".$receiverid . " AND FID = ".$userId. ")" ;
    $result = mysql_query($sql);
    $count = mysql_num_rows ($result);
    closedb($conn);
    if ($count)
        return true;
    else
        return false;

}

function getPairDetails($senderid, $receiverid){
	$conn = connectdb();
	$sql = "SELECT relationid, anonymity,gametype FROM u_gameplay WHERE senderid = $senderid AND receiverid = $receiverid";
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	$returnValue['relation'] = $row['relationid'];
	$returnValue['anonymous'] = $row['anonymity'];
	$returnValue['gametype'] = $row['gametype'];
	return $returnValue;
}

function getBalance($userid){
	$conn = connectdb();
	$sql = "SELECT * FROM u_users WHERE uid = '$userid'";
	$result = mysql_query($sql);
	if (!$result)
	echo('Invalid query error: ' . mysql_error());
	$row = mysql_fetch_assoc($result);
	//echo "<br/> Test :" .  $row['id'];
	$balance = floatval($row['balance']);
	closedb($conn);
	return $balance;
}



function updateBalance($userId, $receiverid, $moneySent, $sender){
	$conn = connectdb();
	$sql = "SELECT * FROM u_users WHERE uid = '$userid'";
	$result = mysql_query($sql);
	if (!$result)
	echo('Invalid query error: ' . mysql_error());
	$row = mysql_fetch_assoc($result);
	//echo "<br/> Test :" .  $row['id'];
	$balance = floatval($row['balance']);
        if($sender)
        {
            $balance = $balance - $moneySent;
            
        }
        else
        {
             $balance = $balance + $moneySent;
        
        }
        $sql = "Update u_users set balance = " .$balance.  " WHERE uid =". $userid;
	closedb($conn);
	return $balance;
}



function getUnpairedUsers(){
	$conn = connectdb();
	$sql = "SELECT * FROM u_users  where uid > 0 order by name";
	$users = mysql_query($sql);
	$usersNotPaired = null;
	while($row = mysql_fetch_assoc($users)){
		$userid = $row['uid'];
		$name = $row['name'];
		$sql = "SELECT * FROM u_gameplay WHERE senderid = " . $userid . " OR receiverid = " . $userid;
		$result = mysql_query($sql);
		$count = mysql_num_rows($result);
		if($count == 0){
			$userArray['id'] = $userid;
			$userArray['name'] =$name;
			$usersNotPaired[] = $userArray;
		}
	}
	closedb($conn);
	return $usersNotPaired;
}
function eliminate_paired($userid){
	$conn = connectdb();
	$sql = "SELECT * FROM u_gameplay WHERE senderid = " . $userid . " OR receiverid = " . $userid;
	$result = mysql_query($sql);
        $count = mysql_num_rows($result);
        if ($count == NULL)
            return true;
        else
            return false;
	
}
function getUsers(){
	$users = null;
	$conn = connectdb();
	$sql = "SELECT * FROM u_users where uid > 0 order by name";
	$result = mysql_query($sql);
	while($row = mysql_fetch_assoc($result)){
		$userid = $row['uid'];
		$name = $row['name'];
		$email = $row['email'];
		$userArray['id'] = $userid;
		$userArray['name'] = $name;
		$userArray['email'] = $email;
		$users[] = $userArray;
	}
	closedb($conn);
	return $users;
}

function getFriendsinApp($userid){
	$conn = connectdb();
	$sql = "select UID from friends where FID = ". $userid ;
	$result = mysql_query($sql);
	$friends = null;
	while($row = mysql_fetch_assoc($result))
	$friends[] = $row['UID'];
	$sql = "select FID from friends where UID = " . $userid;
	$result = mysql_query($sql);
	while($row = mysql_fetch_assoc($result))
	$friends[] = $row['FID'];
	closedb($conn);
	return $friends;
}

function getFriendsinAppOneDegree($userid){
	$conn = connectdb();
	$friends = null;
	$sql = "select u_users.uid as uid from friends, u_users where friends.FID =u_users.uid AND friends.UID = " . $userid;
        $result = mysql_query($sql);
	while($row = mysql_fetch_assoc($result))
        {
                $friends[] = $row['uid'];
        }
	closedb($conn);
        
	return $friends;
}
function getFriendsNotPaired($userid){
	$friends = getFriendsinApp($userid);
	if($friends == null)
            return null;
	$conn = connectdb();
	$friendsNotPaired = null;
	foreach ($friends as $friend){
		if(isUserAdded($friend) == 1){
			$sql = "SELECT * FROM u_gameplay WHERE senderid = " . $friend . " OR receiverid = " . $friend;
			$result = mysql_query($sql);
			$count = mysql_num_rows($result);
			if($count == 0){
				$friendsNotPaired[] = $friend;
			}
		}
	}
	closedb($conn);
	return $friendsNotPaired;
}

function getOneDegreeFriends($userid, $friendid){
	$friends = getFriendsinAppOneDegree($userid);
	$friendsOfFriend = getFriendsinAppOneDegree($friendid);
	$i =0;
	$j = array_search($userid, $friendsOfFriend);
	if($j !== FALSE)
	array_splice($friendsOfFriend, $j, 1);
        $k = array_search($friendid, $friends);
	if($k !== FALSE)
	array_splice($friends, $k, 1);
	for($i =0; $i < count($friends); $i++){
		$index = array_search($friends[$i], $friendsOfFriend);
		if($index !== FALSE)
		array_splice($friendsOfFriend, $index, 1);
	}
	return $friendsOfFriend;
}
function getMaxTreatmentId(){
	$conn = connectdb();
	$sql = "select max(treatmentid) as max from u_gameplay";
	$result = mysql_query($sql);
	$number = 0;
	while($row = mysql_fetch_assoc($result)){
		$max = $row['max'];
		if($max == NULL)
		$max = 0;
	}
	closedb($conn);
	return $max;
}


function getMutualFriendsFromDatabase($userid1, $userid2){
	$conn = connectdb();
	$sql = "select count(Mut_fid) as MFID from mutual_friends where (UID = $userid1 AND FID = $userid2) OR (UID = $userid2 AND FID = $userid1)";
	$result = mysql_query($sql);
	$number = 0;
	while($row = mysql_fetch_assoc($result)){
		$number = $row['MFID'];
	}
	return $number;
}

function deleteUsers($userids){
	$conn = connectdb();

	foreach($userids as $userid){
		$sql = "DELETE from user where UID =".$userid ;
		mysql_query($sql);

		logEvent($userid, NULL, 0, 9);

	}
	closedb($conn);
}
function informRavi($senderid, $receiverid){
	//echo 'Emailing pair details';
	$email = new Mail_Postmark();
	$email->to("lopezgilsinia@gmail.com", 'IOnline Token Sharing Game')
		->subject('Sender - ' . getName($senderid) . ' Receiver - ' . getName($receiverid))
		->messageHtml('Empty')
		->send();
}

function getMutualFriendsFromDatabaseNoConnection($userid1, $userid2){
	$sql = "select count(Mut_fid) as mutualfriends from mutual_friends where (UID = $userid1 AND FID = $userid2) OR (UID = $userid2 AND FID = $userid1)";
	$result = mysql_query($sql);
	$number = 0;
	while($row = mysql_fetch_assoc($result)){
		$number = $row['mutualfriends'];
	}
	return $number;
}

function generateSocialReport(){
	$reportFile = fopen("/var/www/JMJ_test/socialReport.csv", 'c');
	$title = array( "User Id1",  "User1-Name", "User1-Sex", "User1-Email", "User1-No of Friends",  "User1-Wallposts",  "User Id2",  "User2-Name", "User2-Sex", "User2-Email", "User2-No of Friends",  "User2-Wallposts",  "Mutual Friends", "Wallposts Exchanged");
	$conn = connectdb();
	$sql = "select * from friends";
	$result = mysql_query($sql);
	$friends = null;
	fwrite($reportFile, implode(",", $title) . "\n");
	while($row = mysql_fetch_assoc($result)){
		$userId1 = $row['UID'];
		$userId2 = $row['FID'];
		$user1 = getUsersForSocialReport($userId1);
		$user2 = getUsersForSocialReport($userId2);
                $conn = connectdb();
                $Mut_fid= getMutualFriendsFromDatabaseNoConnection($userId1, $userId2);
                closedb($conn);
                $wallpostcount = getwallpostcount($userId1, $userId2);

		$friendDetails = $userId1 . "," . $user1['name'] . "," . $user1['sex'] . "," . $user1['email'] . "," . $user1['friends'] . "," . $user1['wall_count'] .  ",";
		$friendDetails = $friendDetails . $userId2 . "," . $user2['name'] . "," . $user2['sex'] . "," . $user2['email'] . "," . $user2['friends'] . "," . $user2['wall_count'] .",";
		$friendDetails = $friendDetails . $Mut_fid . "," . $wallpostcount ;

		fwrite($reportFile, $friendDetails . "\n");
	}
	fclose($reportFile);
	closedb($conn);
}


function getwallpostcount($user1,$user2)
{
    
    $conn = connectdb();
    if ($con=connectdb())
    {
        $sql = "select * from posts where UID = $user1 AND fromid = $user2 ";
        $result = mysql_query($sql);
        $count = mysql_num_rows($result);
        $sql = "select * from posts where UID = $user2 AND fromid = $user1  ";
        $result = mysql_query($sql);
        $count1 = mysql_num_rows($result);
        $count =$count1 +$count;
        $sql = "select * from posts where UID = $user1 AND toid = $user2 ";
        $result = mysql_query($sql);
        $count1 = mysql_num_rows($result);
        $count =$count1 +$count;
        $sql = "select * from posts where UID = $user2 AND toid = $user1 ";
        $result = mysql_query($sql);
        $count1 = mysql_num_rows($result);
        $count =$count1 +$count;
    }
    closedb($conn);
}

function getUsersForSocialReport($userId){
	$conn = connectdb();
	$sql = "select * from user where UID = $userId";
	$result = mysql_query($sql);
        $row = mysql_fetch_assoc($result);
        $count = mysql_num_rows($result);
        if ($count <= 0 )
        {
            $sql = "select * from friends where FID = $userId";
            $result = mysql_query($sql);
            $row = mysql_fetch_assoc($result);
            $user['name'] = $row['FName'];
            $user['sex'] = 'UNK';
            $user['email'] = 'UNK';
            $user['friends'] = 0;
            $user['wall_count'] = 0;
        }
        else
        {
        $sql1 = "select * from friends where UID = $userId";
        $result1 = mysql_query($sql1);
	$row1 = mysql_fetch_assoc($result1);
        $fcount = mysql_num_rows($result1);
        $sql1 = "select * from status where UID = $userId";
        $result1 = mysql_query($sql1);
	$row1 = mysql_fetch_assoc($result1);
        $scount = mysql_num_rows($result1);
        $user['name'] = $row['Name'];
	$user['sex'] = $row['Gender'];
	$user['email'] = $row['email'];
	$user['friends'] = $fcount;
	$user['wall_count'] = $scount;
        }

	closedb($conn);
	return $user;
}
function addWithinPair($senderid, $receiverid1, $receiverid2, $receiverid3, $receiverid4, $annonymous, $treatmentid){
	srand(time());
	$random = (rand()%4);
	$receiverid = null;
	$dummyReceiver1 = null;
	$dummyReceiver2 = null;
    $dummyReceiver3 = null;

	$anonymous = false;
    $dummyAnonymous1 = false;
    $dummyAnonymous2 = false;
    $dummyAnonymous3 = false;
	$relation = 1;
	$gametype = 2;


	switch ($random){
		case 0:
			$receiverid = $receiverid1;
			$dummyReceiver1 = $receiverid2;
			$dummyReceiver2 = $receiverid3;
            $dummyReceiver3 = $receiverid4;
            break;
		case 1:
			$receiverid = $receiverid2;
			$dummyReceiver1 = $receiverid1;
			$dummyReceiver2 = $receiverid3;
            $dummyReceiver3 = $receiverid4;
			break;
		case 2:
			$receiverid = $receiverid3;
			$dummyReceiver1 = $receiverid1;
			$dummyReceiver2 = $receiverid2;
            $dummyReceiver3 = $receiverid4;
			break;
        case 3:
			$receiverid = $receiverid4;
			$dummyReceiver1 = $receiverid1;
			$dummyReceiver2 = $receiverid2;
            $dummyReceiver3 = $receiverid3;
			break;
    }
	
    switch ($annonymous){
        case $receiverid:
            $anonymous = true;
            break;
        case $dummyReceiver1:
            $dummyAnonymous1 = true;
            break;
        case $dummyReceiver2:
            $dummyAnonymous2 = true;
            break;
        case $dummyReceiver3:
            $dummyAnonymous3 = true;
            break;
    }

        $gametype = 2;




    
    /*
    echo ('<br/>' .$random . ' anonymous:'  . $annonymous . '<br/>');
	echo ('Sender:' . $senderid . ' Receiver:' . $receiverid . ' anonymous:' . $anonymous . '<br/>');
    echo ('Dummy Receiver 1:' . $dummyReceiver1 . ' anonymous:' . $dummyAnonymous1 . '<br/>');
    echo ('Dummy Receiver 2:' . $dummyReceiver2 . ' anonymous:' . $dummyAnonymous2 . '<br/>');
    
    */
	
    
	$conn = connectdb();

	$sql = "SELECT id FROM u_states where state LIKE \"Notification Sent\"";
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	$stateid = $row['id'];

	$mutualFriend = getMutualFriendsFromDatabaseNoConnection($senderid, $receiverid);
	$sql = "INSERT INTO u_gameplay (senderid, receiverid, stateid, relationid, anonymity, treatmentid, mutualFriend,gametype) VALUES ('$senderid', '$receiverid', '$stateid', '$relation', '$anonymous', '$treatmentid', '$mutualFriend','$gametype')";
	$result = mysql_query($sql);
	if (!$result) {
		echo('Invalid query: ' . mysql_error());
	}else{
		$sql = "UPDATE u_users SET balance = " . game_amount . " WHERE uid = '$senderid'";
		mysql_query($sql);
		$senderMsg = 'Congratulations! You have been selected to play the Online Token Sharing  Game on Facebook as a sender. <br/><br/> '.
					 '<a href="http://apps.facebook.com/trustgame/selected.php">Please click here to proceed further.</a> It will only take a minute. Good luck and have fun!'.
					 '<br/><br/>Please note that this is a limited time opportunity and you have to click the above link and make your move to earn your cash payoffs.' .
					 '<br/><br/><br/><strong>ABOUT THE GAME</strong>'.
					 '<br/>Recently you signed up for the opportunity to participate in our field study. We are a team of researchers from University of Minnesota and University of Connecticut conducting a field experiment on social networking and trust. This study is funded by multiple research grants from the above mentioned institutions and conforms contemporary behavioral research protocol. It has been approved by our respective institutions Institutional Review Boards.';

		$email = new Mail_Postmark();
		$email->to(getEmail($senderid), 'Online Token Sharing  Game Administrator')
		->subject('You are the sender !!!')
		->messageHtml($senderMsg)
		->send();
                informRavi($senderid, $receiverid);
		logEvent($senderid, $receiverid, 0, 3);
	}

	/*$mutualFriend = getMutualFriendsFromDatabaseNoConnection($senderid, $dummyReceiver1);
	$sql = "INSERT INTO withingameplay (senderid, receiverid, mutualFriend, anonymity) VALUES ('$senderid', '$dummyReceiver1', '$mutualFriend', '$dummyAnonymous1')";
	$result = mysql_query($sql);
	if (!$result)
	echo('Invalid query dummy insert 1: ' . mysql_error());

	$mutualFriend = getMutualFriendsFromDatabaseNoConnection($senderid, $dummyReceiver2);
        //TODO : check what withingameplay is
	$sql = "INSERT INTO withingameplay (senderid, receiverid, mutualFriend, anonymity) VALUES ('$senderid', '$dummyReceiver2', '$mutualFriend', '$dummyAnonymous2')";
	$result = mysql_query($sql);
	if (!$result)
	echo('Invalid query dummy insert 2: ' . mysql_error());
    
        $mutualFriend = getMutualFriendsFromDatabaseNoConnection($senderid, $dummyReceiver3);
	$sql = "INSERT INTO withingameplay (senderid, receiverid, mutualFriend, anonymity) VALUES ('$senderid', '$dummyReceiver3', '$mutualFriend', '$dummyAnonymous3')";
	$result = mysql_query($sql);
	if (!$result)
	echo('Invalid query dummy insert 3: ' . mysql_error());*/

	closedb($conn);
    
}
function addPair($id1, $id2, $relation, $anonymous, $treatmentid, $mutualFriend){
       
	srand(time());
	$random = (rand()%2);
	$receiverid = $id1;
	$senderid = $id2;
	if( $random == 0 ){
		$receiverid = $id2;
		$senderid = $id1;
	}
	$conn = connectdb();
	$sql = "SELECT id FROM u_states where state LIKE \"Notification Sent\"";
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
	$stateid = $row['id'];

	if($relation != null){
		if($relation != 4)
		$sql = "INSERT INTO u_gameplay (senderid, receiverid, stateid, relationid, anonymity, treatmentid) VALUES ('$senderid', '$receiverid', '$stateid', '$relation', '$anonymous', '$treatmentid')";
		else
		$sql = "INSERT INTO u_gameplay (senderid, receiverid, stateid, relationid, anonymity, treatmentid, mutualFriend) VALUES ('$senderid', '$receiverid', '$stateid', '$relation', '$anonymous', '$treatmentid', '$mutualFriend')";
	}
	else{
		$relation = 1;
		$sql = "INSERT INTO u_gameplay (senderid, receiverid, stateid, treatmentid) VALUES ('$senderid', '$receiverid', '$stateid', '$treatmentid')";
	}
        
        
	$result = mysql_query($sql);
	if (!$result) {
		echo('Invalid query: ' . mysql_error());
	}else{
		$sql = "UPDATE u_users SET balance = " . game_amount . " WHERE uid = '$senderid'";
		mysql_query($sql);
		$senderFriendMsg = '';
		$receiverFriendMsg = '';
		if($anonymous){
			if($relation == 1){
				$senderFriendMsg = 'You have been paired with an <strong>anonymous facebook user.</strong> ';
				$receiverFriendMsg = 'You have been paired with an <strong>anonymous facebook user.</strong> ';
			}else if($relation == 2 || $relation == 3){
				$senderFriendMsg = 'You have been paired with an <strong>anonymous facebook friend.</strong> ';
				$receiverFriendMsg = 'You have been paired with an <strong>anonymous facebook friend.</strong> ';
			}else if($relation == 4){
				$senderFriendMsg = 'You have been paired with an <strong>anonymous facebook user you is a friend of one of your friends.</strong> ';
				$receiverFriendMsg = 'You have been paired with an <strong>anonymous facebook user you is a friend of one of your friends.</strong> ';
			}
		}else{
			if($relation == 1){
				$senderFriendMsg = 'You have been paired with  <a href="http://www.facebook.com/profile.php?id='. $receiverid . '">'. getName($receiverid) . '</a>. ';
				$receiverFriendMsg = 'You have been paired with <a href="http://www.facebook.com/profile.php?id='.$senderid.'">'. getName($senderid) . '</a>. ';
			}else if($relation == 2){
				$senderFriendMsg = 'You have been paired with  <strong>your friend</strong> <a href="http://www.facebook.com/profile.php?id='.$receiverid.'">'. getName($receiverid) . '</a>. <strong>Note that you do not share any mutual friends with ' . getName($receiverid) . '.</strong> ';
				$receiverFriendMsg = 'You have been paired with <strong>your friend</strong> <a href="http://www.facebook.com/profile.php?id='.$senderid.'">'. getName($senderid) . '</a>. <strong>Note that you do not share any mutual friends with ' . getName($senderid) . '. </strong>';
			}else if($relation == 3){
				$senderFriendMsg = 'You have been paired with  <strong>your friend</strong> <a href="http://www.facebook.com/profile.php?id='.$receiverid.'">'. getName($receiverid) . '</a>. ';
				$receiverFriendMsg = 'You have been paired with <strong>your friend</strong> <a href="http://www.facebook.com/profile.php?id='.$senderid.'">'. getName($senderid) . '</a>. ';
			}else if($relation == 4){
				$senderFriendMsg = 'You have been paired with  <a href="http://www.facebook.com/profile.php?id='. $receiverid . '">'. getName($receiverid) . '</a> who is a <strong>friend of <a href="http://www.facebook.com/profile.php?id='. $mutualFriend . '">'. getName($mutualFriend) . '</a>.</strong> ';
				$receiverFriendMsg = 'You have been paired with  <a href="http://www.facebook.com/profile.php?id='.$senderid.'">'. getName($senderid) . '</a> who is a <strong>friend of <a href="http://www.facebook.com/profile.php?id='. $mutualFriend . '">'. getName($mutualFriend) . '</a>.</strong> ' ;
			}

		}
              if($senderid == 0)
		{
			$senderid=$receiverid;
			echo "I came here";
			$receiverid ==-1;
		}
		$sendermsg = 'Congratulations! You have been selected to play our Online Token Sharing Game on Facebook! <br/><br/> '.
					 'Recently you signed up for the opportunity to participate in our field study. We are a team of researchers from University of Minnesota  conducting a field experiment on social networking and trust. This study is funded by multiple research grants from the above mentioned institution and conforms contemporary behavioral research protocol. It has been approved by our respective institutions Institutional Review Boards.<br/><br/>'.
		$senderFriendMsg .
					 'You will be the sender for this game.<br/><br/>' .
					 '<a href="http://apps.facebook.com/jmj_testa/selected.php">Please click here to proceed further.</a> Good luck and have fun!'.
					 '<br/><br/>Please note that both you and your receiver have to complete the game to earn your payoffs.';
		$email = new Mail_Postmark();
		$email->to(getEmail($senderid), 'Online Token Sharing Game Administrator')
		->subject('You are the sender !!!')
		->messageHtml($sendermsg)
		->send();
		if($receiverid > 0)
		{
		$receivermsg = 'Congratulations! You have been selected to play our Online Token Sharing Game on Facebook! <br/> <br/>'.
					 'Recently you signed up for the opportunity to participate in our field study. We are a team of researchers from University of Minnesota conducting a field experiment on social networking and trust. This study is funded by multiple research grants from the above mentioned institution and conforms contemporary behavioral research protocol. It has been approved by our respective institutions Institutional Review Boards.<br/><br/>'.
		$receiverFriendMsg .
					 'You will be the receiver for this game.<br/><br/>'.
					 'Please wait for the sender to respond. You will receive a mail as soon as the sender responds. Good luck and have fun!'.
					 '<br/><br/>Please note that both you and your sender have to complete the game to earn your payoffs.';
		$email = new Mail_Postmark();
		$email->to(getEmail($receiverid), 'Online Token Sharing Game Administrator')
		->subject('You are the receiver !!!')
		->messageHtml($receivermsg)
		->send();
		}
		logEvent($senderid, $receiverid, 0, 3);

	}

	closedb($conn);
	return $receiverid;
}